package com.travel.Service.Impl;

import com.travel.Bean.User;
import com.travel.Config.Security_PasswordEncoder;
import com.travel.JPA.UserJPA;
import com.travel.util.AES;
import com.travel.util.ConsoleOutputControl;
import com.travel.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl {

    @Autowired
    private UserJPA userJPA;

    @Autowired
    private RedisUtil redisUtil;

    private final String RedisMailSetName = "MailSet";
    private final String RedisPhoneSetName = "PhoneSet";


    public boolean userRegistration(User user) throws Exception {
        String pwd = user.getPassword();
        //加密用户密码
        user.setPassword(AES.encrypt(pwd, Security_PasswordEncoder.secretKey));
        //保存用户信息
        try{
            userJPA.save(user);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        //将已注册的邮箱和手机号写入redis
        if (!redisUtil.setAdd(RedisMailSetName,user.getMail())){
            System.out.println(ConsoleOutputControl.getColoredOutputString("邮箱Redis缓存异常，注册邮箱无法写入", 33));
        }
        if(!redisUtil.setAdd(RedisPhoneSetName,user.getPhone()))
            System.out.println(ConsoleOutputControl.getBackgroundColoredOutputString("手机号Redis缓存异常，注册手机无法写入", 33));


        return true;
    }



    /**
     * 用户邮件重复
     *
     * @param userMail 用户邮件
     * @return boolean
     */
    public boolean userMailRepetition(String userMail){
        return !redisUtil.setMember(RedisMailSetName, userMail);
    }

    /**
     * 用户电话重复
     *
     * @param userPhone 用户电话
     * @return boolean
     */
    public boolean userPhoneRepetition(String userPhone){
        return !redisUtil.setMember(RedisPhoneSetName, userPhone);
    }


    /**
     * 得到用户邮件
     *
     * @return {@link List}<{@link String}>
     */
    public List<String> getUserMail(){
        return userJPA.findUserMail();
    }

    /**
     * 获取用户手机
     *
     * @return {@link List}<{@link String}>
     */
    public List<String> getUserPhone(){
        return userJPA.findUserPhone();
    }




}
